package com.itcc.service.impl;

import com.itcc.dao.CartDao;
import com.itcc.dao.OrdersDao;
import com.itcc.dao.impl.CartDaoImpl;
import com.itcc.dao.impl.OrderDaoImpl;
import com.itcc.entity.*;
import com.itcc.service.OrdersService;
import com.itcc.utils.RandomUtils;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class OrdersServiceImpl implements OrdersService {
    @Override
    public void createOrder(String aid, String uid, String sum) throws SQLException, InvocationTargetException, IllegalAccessException {

        Orders orders = new Orders();
        String orderId = RandomUtils.createOrderId();
        orders.setOid(orderId);
        orders.setAid(Integer.parseInt(aid));
        orders.setUid(Integer.parseInt(uid));
        BigDecimal bsum=new BigDecimal(sum);
        orders.setOcount(bsum);
        orders.setOstate(1);//未支付
        orders.setOtime(new Date());

        OrdersDao ordersDao=new OrderDaoImpl();
        ordersDao.insertOrders(orders);

        CartDao cartDao=new CartDaoImpl();
        List<Cart> carts = cartDao.selectCartsByUid(Integer.parseInt(uid));
        List<Item> items=new ArrayList<>();

        for (Cart cart : carts) {
            Item item = new Item();
            item.setOid(orders.getOid());
            item.setIcount(cart.getCcount());
            item.setInum(cart.getCnum());
            item.setPid(cart.getProduct().getPid());

            items.add(item);
        }

        //保存订单项
        ordersDao.insertItems(items);

        //清空购物车
        cartDao.deleteCartByUid(uid);

    }

    @Override
    public List<Orders> findOrdersByUid(int uid) throws SQLException, InvocationTargetException, IllegalAccessException {

        OrdersDao ordersDao=new OrderDaoImpl();
        List<Orders> list=ordersDao.selectOrdersByUid(uid);

        return list;
    }

    @Override
    public Orders findOrdersByOid(String oid) throws SQLException, InvocationTargetException, IllegalAccessException {

        OrdersDao ordersDao=new OrderDaoImpl();
        Orders orders=ordersDao.selectOrderByOid(oid);

        List<Item> items=ordersDao.selectItemsByOid(oid);

        orders.setItems(items);

        return orders;
    }

    @Override
    public void updateStatusByOid(String oid) throws SQLException {
        OrdersDao ordersDao=new OrderDaoImpl();
        ordersDao.updateStatusByOid(oid);
    }

    @Override
    public List<Orders> findAllOrders() throws SQLException {

        OrdersDao ordersDao=new OrderDaoImpl();
        List<Orders> ordersList=ordersDao.findAllOrders();

        return ordersList;
    }
}
